package com.startsmake.llrisetabbardemo.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.tabbar.demo.R;
import com.tabbar.demo.retrofit.RequestService;
import com.tabbar.demo.util.ToolLog;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class RetrofitTestActivity extends AppCompatActivity {
    public final static String URL_BASE = "https://api.github.com/users/";
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit_test);
        initView();
        initRetrofit();
    }

    private void initRetrofit() {

        //步骤2，实例化Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(URL_BASE)
                .build();
        //3、通过Retrofit实例创建接口服务对象
        RequestService requestService = retrofit.create(RequestService.class);
        //4、接口服务对象调用接口中方法，获得Call对象
        Call<RequestBody> call = requestService.getString();
        // 5、Call对象执行请求（异步、同步请求）
        call.enqueue(new Callback<RequestBody>() {
            @Override
            public void onResponse(Call<RequestBody> call, Response<RequestBody> response) {
                try {
                    ToolLog.i("http", response.body().toString());
                    //返回的结果保存在response.body()中
                    String result = response.body().toString();
                    //onResponse方法是运行在主线程也就是UI线程的，所以我们可以在这里
                    //直接更新UI
                    textView.setText(result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<RequestBody> call, Throwable t) {
                ToolLog.w("http","request fail");
            }
        });
    }

    private void initView() {
        textView = (TextView) findViewById(R.id.textView);
    }
}
